package com.yunchang.springboot.scheduled.MWS;

import com.amazon.mws.finances._2015_05_01.MWSFinancesServiceAsync;
import com.amazon.mws.finances._2015_05_01.MWSFinancesServiceAsyncClient;
import com.amazon.mws.finances._2015_05_01.MWSFinancesServiceException;
import com.amazon.mws.finances._2015_05_01.model.*;
import com.amazon.mws.finances._2015_05_01.model.Currency;
import com.amazonservices.mws.client.MwsUtl;
import com.yunchang.springboot.config.MWS.MWSFinancesDataServiceConfig;
import com.yunchang.springboot.mapper.mws.finances.MwsFinancesEventGroupMapper;
import com.yunchang.springboot.mapper.mws.finances.MwsFinancesFinancialReportMapper;
import com.yunchang.springboot.mapper.mws.finances.MwsFinancesInfrequentlyUsedMapper;
import com.yunchang.springboot.mapper.shop.ShopAreaMapper;
import com.yunchang.springboot.mapper.shop.ShopMapper;
import com.yunchang.springboot.models.DO.mws.finances.MwsFinancesEventGroup;
import com.yunchang.springboot.models.DO.mws.finances.MwsFinancesFinancialReport;
import com.yunchang.springboot.models.DO.mws.finances.MwsFinancesInfrequentlyUsed;
import com.yunchang.springboot.models.Shop;
import com.yunchang.springboot.utils.AreaCastUtil;
import com.yunchang.springboot.utils.CryptoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.xml.datatype.XMLGregorianCalendar;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Slf4j
@Service
public class MwsFinancesEventReportSchedule {
    @Resource
    ShopMapper shopMapper;
    @Resource
    ShopAreaMapper shopAreaMapper;
    @Resource
    MwsFinancesFinancialReportMapper mwsFinancesFinancialReportMapper;
    @Resource
    MwsFinancesEventGroupMapper mwsFinancesEventGroupMapper;
    @Resource
    MwsFinancesInfrequentlyUsedMapper mwsFinancesInfrequentlyUsedMapper;

    /**
     * 错误重试次数
     */
    private static final Integer MAX_ERROR_NUM = 3;

    @Scheduled(cron = "00 00 01 * * ?")
    public void getFinancesData(){
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String postedDate = mwsFinancesFinancialReportMapper.getLatestPostedDate();
        LocalDateTime startTime = LocalDateTime.parse(postedDate,df).minusSeconds(-1);
        LocalDateTime nowTime = LocalDateTime.now();
        LocalDateTime endTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,0,0,0);
        log.info("开始" + startTime + "到" + endTime + "的mws finance数据拉取任务");
        getFinancesDataList(startTime,endTime);
    }

    /**
     * 获得mwsFinances的数据，先获取finances groupID，然后根据groupID去拿指定账期的财务数据，
     * 这里的区域需要去各种events里确定（因为广告的财务数据不区分具体的国家，在欧洲区域的店就区分不出来）
     */
    @Transactional(rollbackFor = Exception.class)
    public void getFinancesDataList(LocalDateTime startTime, LocalDateTime endTime) {
        //获得当前日期时间
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //LocalDateTime nowDateTime = LocalDateTime.now().minusDays(2);
//        LocalDateTime nowDateTime = LocalDateTime.of(2020,1,7,0,0,0);
        LocalDateTime nowDateTime = endTime;
        int nowYear = nowDateTime.getYear();
        int nowMonth = nowDateTime.getMonthValue();
        int nowDay = nowDateTime.getDayOfMonth();
        int nowHour = nowDateTime.getHour();
        //nowDateTime = LocalDateTime.of(nowYear, nowMonth, nowDay, nowHour, 0, 0);
//        LocalDateTime preDateTime = nowDateTime.minusDays(1);
        //LocalDateTime preDateTime = LocalDateTime.of(2020, 3, 1, 0, 0, 0);
        LocalDateTime preDateTime = startTime;
        int preYear = preDateTime.getYear();
        int preMonth = preDateTime.getMonthValue();
        int preDay = preDateTime.getDayOfMonth();
        int preHour = preDateTime.getHour();
        List<Shop> shopList = shopMapper.getAllList();
        //直接根据店铺、区域来生成client
        for (Shop shop : shopList) {
            String awsAccessKeyId = CryptoUtil.decode(shop.getAwsAccessKeyId());
            String secretKey = CryptoUtil.decode(shop.getSecretKey());
            String brandName = shop.getBrandName();
            String sellerId = CryptoUtil.decode(shop.getSellerId());
            String mwsAuthToken = CryptoUtil.decode(shop.getMwsAuthToken());
            //获得这个店铺对应的大区域信息region_code
            String regionCode = shopAreaMapper.getRegionCodeByShopId(shop.getId());
            String serviceURL;
            if ("NA".equals(regionCode)) {
                serviceURL = "https://mws.amazonservices.com";
            } else if ("EU".equals(regionCode)) {
                serviceURL = "https://mws-eu.amazonservices.com";
            } else if ("FE".equals(regionCode)) {
                serviceURL = "https://mws.amazonservices.jp";
            } else {
                serviceURL = "https://mws.amazonservices.com";
            }
            //创建对应的实例
            log.info("-------开始创建awsAccessKeyId：" + awsAccessKeyId + ",secretKey:" + secretKey + ",serviceURL:" + serviceURL + "的实例--------");
            MWSFinancesServiceAsyncClient client = MWSFinancesDataServiceConfig.getAsyncClient(awsAccessKeyId, secretKey, serviceURL);
            List<ListFinancialEventGroupsRequest> listFinancialEventGroupsRequestList = new ArrayList<ListFinancialEventGroupsRequest>();
            ListFinancialEventGroupsRequest listFinancialEventGroupsRequest = new ListFinancialEventGroupsRequest();
            listFinancialEventGroupsRequest.setSellerId(sellerId);
            listFinancialEventGroupsRequest.setMWSAuthToken(mwsAuthToken);
            XMLGregorianCalendar financialEventGroupStartedAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
            financialEventGroupStartedAfter.setYear(preYear);
            financialEventGroupStartedAfter.setMonth(preMonth);
            financialEventGroupStartedAfter.setDay(preDay);
            financialEventGroupStartedAfter.setTime(preHour, 0, 0);
            listFinancialEventGroupsRequest.setFinancialEventGroupStartedAfter(financialEventGroupStartedAfter);
            XMLGregorianCalendar financialEventGroupStartedBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
            financialEventGroupStartedBefore.setYear(nowYear);
            financialEventGroupStartedBefore.setMonth(nowMonth);
            financialEventGroupStartedBefore.setDay(nowDay);
            financialEventGroupStartedBefore.setTime(nowHour, 0, 0);
            listFinancialEventGroupsRequest.setFinancialEventGroupStartedBefore(financialEventGroupStartedBefore);
            Integer maxResultsPerPage = 100;
            listFinancialEventGroupsRequest.setMaxResultsPerPage(maxResultsPerPage);
            listFinancialEventGroupsRequestList.add(listFinancialEventGroupsRequest);
            //获得规定时间内所有的groupID
            System.out.println("-------------------------------------------groupId开始---------------------------------------------------------");
            List<FinancialEventGroup> financialEventGroupList = invokeListFinancialEventGroups(client, listFinancialEventGroupsRequestList);
            System.out.println("-------------------------------------------groupId结束---------------------------------------------------------");
            //获取这些groupID中的财务数据
            System.out.println("----------------------------------------financesEvents开始-----------------------------------------------------");
            List<ListFinancialEventsRequest> listFinancialEventsRequestList = new ArrayList<ListFinancialEventsRequest>();
            for (FinancialEventGroup financialEventGroup : financialEventGroupList) {
                ListFinancialEventsRequest listFinancialEventsRequest = new ListFinancialEventsRequest();
                listFinancialEventsRequest.setSellerId(sellerId);
                listFinancialEventsRequest.setMWSAuthToken(mwsAuthToken);
                listFinancialEventsRequest.setMaxResultsPerPage(maxResultsPerPage);
                String financialEventGroupId = financialEventGroup.getFinancialEventGroupId();
                listFinancialEventsRequest.setFinancialEventGroupId(financialEventGroupId);
                XMLGregorianCalendar postedAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
                postedAfter.setYear(preYear);
                postedAfter.setMonth(preMonth);
                postedAfter.setDay(preDay);
                postedAfter.setTime(preHour, 0, 0);
                listFinancialEventsRequest.setPostedAfter(postedAfter);
                XMLGregorianCalendar postedBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
                postedBefore.setYear(nowYear);
                postedBefore.setMonth(nowMonth);
                postedBefore.setDay(nowDay);
                postedBefore.setTime(nowHour, 0, 0);
                listFinancialEventsRequest.setPostedBefore(postedBefore);
                listFinancialEventsRequestList.add(listFinancialEventsRequest);
            }
            HashMap<String, List<FinancialEvents>> financialEventsListMap = invokeListFinancialEvents(client, listFinancialEventsRequestList);
            System.out.println("----------------------------------------financesEvents结束-----------------------------------------------------");
            System.out.println("-----------------------------------开始存储financesEvents的数据-------------------------------------------------");
            HashMap<String, List> stringListHashMap = packageFinancialEventsAndGroup(financialEventsListMap, financialEventGroupList, shop.getSellerId(), brandName);
            List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList = stringListHashMap.get("mwsFinancesFinancialReportList");
            if (mwsFinancesFinancialReportList != null && mwsFinancesFinancialReportList.size() != 0) {
                mwsFinancesFinancialReportMapper.insertList(mwsFinancesFinancialReportList);
            }
            System.out.println("-----------------------------------存储financesEvents的数据成功-------------------------------------------------");
            System.out.println("---------------------------------------开始存储GroupId的数据----------------------------------------------------");
            List<MwsFinancesEventGroup> mwsFinancesEventGroupList = stringListHashMap.get("mwsFinancesEventGroupList");
            if (mwsFinancesEventGroupList != null && mwsFinancesEventGroupList.size() != 0) {
                mwsFinancesEventGroupMapper.replaceDataList(mwsFinancesEventGroupList);
            }
            System.out.println("---------------------------------------存储GroupId的数据成功----------------------------------------------------");
            log.info("以上，获取sellerID为：" + sellerId + "，店铺名称为：" + brandName + "的店铺的财务数据完成");
            List<MwsFinancesInfrequentlyUsed> mwsFinancesInfrequentlyUsedList = stringListHashMap.get("mwsFinancesInfrequentlyUsedList");
            if (mwsFinancesInfrequentlyUsedList != null && mwsFinancesInfrequentlyUsedList.size() != 0) {
                mwsFinancesInfrequentlyUsedMapper.insertList(mwsFinancesInfrequentlyUsedList);
            }
        }
        log.info("-------------------------------以上，所有店铺的财务数据完成-------------------------------");
    }


    /**
     * 异步调用finances groupID
     */
    public static List<FinancialEventGroup> invokeListFinancialEventGroups(MWSFinancesServiceAsync client, List<ListFinancialEventGroupsRequest> requestList) {
        List<FinancialEventGroup> financialEventGroupList = new ArrayList<>();
        for (ListFinancialEventGroupsRequest request : requestList) {
            String sellerId = request.getSellerId();
            String mwsAuthToken = request.getMWSAuthToken();
            log.info("开始获取sellerId为：" + sellerId + "的财务数据的账期id");
            try {
                NUM:
                for (int i = 0; i < MAX_ERROR_NUM; i++) {
                    Future<ListFinancialEventGroupsResponse> future = client.listFinancialEventGroupsAsync(request);
                    ListFinancialEventGroupsResponse response = future.get();
                    ListFinancialEventGroupsResult listFinancialEventGroupsResult = response.getListFinancialEventGroupsResult();
                    financialEventGroupList.addAll(listFinancialEventGroupsResult.getFinancialEventGroupList());
                    //获得nextToken
                    String nextToken = listFinancialEventGroupsResult.getNextToken();
                    if (nextToken != null) {
                        financialEventGroupList = getFinancialEventGroupsListByNextToken(financialEventGroupList, client, sellerId, mwsAuthToken, nextToken);
                    }
                    System.out.println("groupId Size:" + financialEventGroupList.size());
                    log.info("获取sellerId为：" + sellerId + "的财务数据的账期id结束");
                    break NUM;
                }
            } catch (ExecutionException ee) {
                Throwable cause = ee.getCause();
                if (cause instanceof MWSFinancesServiceException) {
                    // Exception properties are important for diagnostics.
                    MWSFinancesServiceException ex =
                            (MWSFinancesServiceException) cause;
//                    ResponseHeaderMetadata rhmd = ex.getResponseHeaderMetadata();
//                    System.out.println("当前线程：" + Thread.currentThread().getName());
//                    System.out.println("Service Exception:");
//                    //System.out.println("RequestId: " + rhmd.getRequestId());
//                    //System.out.println("Timestamp: " + rhmd.getTimestamp());
//                    System.out.println("Message: " + ex.getMessage());
//                    System.out.println("StatusCode: " + ex.getStatusCode());
//                    System.out.println("ErrorCode: " + ex.getErrorCode());
//                    System.out.println("ErrorType: " + ex.getErrorType());
                    try {
                        if (ex.getStatusCode() == 503) {
                            System.out.println("睡眠2.1秒");
                            Thread.sleep(2100);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return financialEventGroupList;
    }

    /**
     * 获取下一页的groupID.
     */
    public static List<Object> invokeListFinancialEventGroupsByNextToken(MWSFinancesServiceAsync client, List<ListFinancialEventGroupsByNextTokenRequest> requestList) {
        // Call the service async.
        List<Object> responseList = new ArrayList<Object>();
        for (ListFinancialEventGroupsByNextTokenRequest request : requestList) {
            NUM:
            for (int i = 0; i < MAX_ERROR_NUM; i++) {
                try {
                    Future<ListFinancialEventGroupsByNextTokenResponse> future = client.listFinancialEventGroupsByNextTokenAsync(request);
                    Object xresponse;
                    ListFinancialEventGroupsByNextTokenResponse response = future.get();
                    xresponse = response;
                    responseList.add(xresponse);
                    log.info("获取下一页groupId成功");
                    break NUM;
                } catch (ExecutionException ee) {
                    Throwable cause = ee.getCause();
                    if (cause instanceof MWSFinancesServiceException) {
                        // Exception properties are important for diagnostics.
                        MWSFinancesServiceException ex =
                                (MWSFinancesServiceException) cause;
//                        ResponseHeaderMetadata rhmd = ex.getResponseHeaderMetadata();
//                        System.out.println("Service Exception:");
//                        System.out.println("RequestId: " + rhmd.getRequestId());
//                        System.out.println("Timestamp: " + rhmd.getTimestamp());
//                        System.out.println("Message: " + ex.getMessage());
//                        System.out.println("StatusCode: " + ex.getStatusCode());
//                        System.out.println("ErrorCode: " + ex.getErrorCode());
//                        System.out.println("ErrorType: " + ex.getErrorType());
                        try {
                            if (ex.getStatusCode() == 503) {
                                System.out.println("睡眠2.1秒");
                                Thread.sleep(2100);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        ee.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return responseList;
    }

    /**
     * 获取下一页订单数据的递归方法
     */
    private static List<FinancialEventGroup> getFinancialEventGroupsListByNextToken(List<FinancialEventGroup> financialEventGroupList, MWSFinancesServiceAsync client, String sellerId, String mwsAuthToken, String nextToken) {
        //准备接口需要的数据
        List<ListFinancialEventGroupsByNextTokenRequest> listFinancialEventGroupsByNextTokenRequests = new ArrayList<ListFinancialEventGroupsByNextTokenRequest>();
        ListFinancialEventGroupsByNextTokenRequest listFinancialEventGroupsByNextTokenRequest = new ListFinancialEventGroupsByNextTokenRequest();
        listFinancialEventGroupsByNextTokenRequest.setSellerId(sellerId);
        listFinancialEventGroupsByNextTokenRequest.setMWSAuthToken(mwsAuthToken);
        listFinancialEventGroupsByNextTokenRequest.setNextToken(nextToken);
        listFinancialEventGroupsByNextTokenRequests.add(listFinancialEventGroupsByNextTokenRequest);
        List<Object> listOrdersByNextTokenList = invokeListFinancialEventGroupsByNextToken(client, listFinancialEventGroupsByNextTokenRequests);
        ListFinancialEventGroupsByNextTokenResponse listFinancialEventGroupsByNextTokenResponse = (ListFinancialEventGroupsByNextTokenResponse) (listOrdersByNextTokenList.get(0));
        financialEventGroupList.addAll(listFinancialEventGroupsByNextTokenResponse.getListFinancialEventGroupsByNextTokenResult().getFinancialEventGroupList());
        String nextToken1 = listFinancialEventGroupsByNextTokenResponse.getListFinancialEventGroupsByNextTokenResult().getNextToken();
        if (nextToken1 != null) {
            getFinancialEventGroupsListByNextToken(financialEventGroupList, client, sellerId, mwsAuthToken, nextToken1);
        }
        return financialEventGroupList;
    }


    /**
     * 异步调用finances报告
     */
    public static HashMap<String, List<FinancialEvents>> invokeListFinancialEvents(MWSFinancesServiceAsync client, List<ListFinancialEventsRequest> requestList) {
        HashMap<String, List<FinancialEvents>> resultMap = new HashMap<>();
        for (ListFinancialEventsRequest request : requestList) {
            List<FinancialEvents> financialEventsList = new ArrayList<>();
            String sellerId = request.getSellerId();
            String mwsAuthToken = request.getMWSAuthToken();
            String groupId = request.getFinancialEventGroupId();
            log.info("开始获取groupId为：" + groupId + "的财务数据");
            try {
                NUM:
                for (int i = 0; i < MAX_ERROR_NUM; i++) {
                    Future<ListFinancialEventsResponse> future = client.listFinancialEventsAsync(request);
                    ListFinancialEventsResponse response = future.get();
                    ListFinancialEventsResult listFinancialEventsResult = response.getListFinancialEventsResult();
                    financialEventsList.add(listFinancialEventsResult.getFinancialEvents());
                    //获得nextToken
                    String nextToken = listFinancialEventsResult.getNextToken();
                    if (null != nextToken) {
                        financialEventsList = getFinancialEventsListByNextToken(financialEventsList, client, sellerId, mwsAuthToken, nextToken);
                    }
                    System.out.println("当前groupId：" + groupId + "的financesEvents size:" + financialEventsList.size());
                    resultMap.put(groupId, financialEventsList);
                    log.info("获取sellerId为：" + sellerId + "的财务数据结束");
                    break NUM;
                }
            } catch (ExecutionException ee) {
                Throwable cause = ee.getCause();
                if (cause instanceof MWSFinancesServiceException) {
                    // Exception properties are important for diagnostics.
                    MWSFinancesServiceException ex =
                            (MWSFinancesServiceException) cause;
//                    ResponseHeaderMetadata rhmd = ex.getResponseHeaderMetadata();
//                    System.out.println("Service Exception:");
//                    System.out.println("RequestId: " + rhmd.getRequestId());
//                    System.out.println("Timestamp: " + rhmd.getTimestamp());
//                    System.out.println("Message: " + ex.getMessage());
//                    System.out.println("StatusCode: " + ex.getStatusCode());
//                    System.out.println("ErrorCode: " + ex.getErrorCode());
//                    System.out.println("ErrorType: " + ex.getErrorType());
                    try {
                        if (ex.getStatusCode() == 503) {
                            System.out.println("睡眠2.1秒");
                            Thread.sleep(2100);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultMap;
    }

    /**
     * 获取下一页的财务报告数据.
     *
     * @param client
     * @param requestList
     * @return The response.
     */
    public static List<Object> invokeListFinancialEventsByNextToken(MWSFinancesServiceAsync client, List<ListFinancialEventsByNextTokenRequest> requestList) {
        log.info("获取下一页的财务数据开始");
        List<Future<ListFinancialEventsByNextTokenResponse>> futureList = new ArrayList<Future<ListFinancialEventsByNextTokenResponse>>();
        List<Object> responseList = new ArrayList<Object>();
        for (ListFinancialEventsByNextTokenRequest request : requestList) {
            NUM:
            for (int i = 0; i < MAX_ERROR_NUM; i++) {
                try {
                    Future<ListFinancialEventsByNextTokenResponse> future = client.listFinancialEventsByNextTokenAsync(request);
                    Object xresponse;
                    ListFinancialEventsByNextTokenResponse response = future.get();
                    xresponse = response;
                    responseList.add(xresponse);
                    log.info("获取下一页的财务数据结束");
                    break NUM;
                } catch (ExecutionException ee) {
                    Throwable cause = ee.getCause();
                    if (cause instanceof MWSFinancesServiceException) {
                        // Exception properties are important for diagnostics.
                        MWSFinancesServiceException ex =
                                (MWSFinancesServiceException) cause;
//                        ResponseHeaderMetadata rhmd = ex.getResponseHeaderMetadata();
//                        System.out.println("Service Exception:");
//                        System.out.println("RequestId: " + rhmd.getRequestId());
//                        System.out.println("Timestamp: " + rhmd.getTimestamp());
//                        System.out.println("Message: " + ex.getMessage());
//                        System.out.println("StatusCode: " + ex.getStatusCode());
//                        System.out.println("ErrorCode: " + ex.getErrorCode());
//                        System.out.println("ErrorType: " + ex.getErrorType());
                        try {
                            if (ex.getStatusCode() == 503) {
                                System.out.println("睡眠2.1秒");
                                Thread.sleep(2100);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        ee.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return responseList;
    }

    /**
     * 获取下一页财务报告数据的递归方法
     */
    private static List<FinancialEvents> getFinancialEventsListByNextToken(List<FinancialEvents> financialEventsList, MWSFinancesServiceAsync client, String sellerId, String mwsAuthToken, String nextToken) {
        //准备接口需要的数据
        List<ListFinancialEventsByNextTokenRequest> listFinancialEventsByNextTokenRequests = new ArrayList<ListFinancialEventsByNextTokenRequest>();
        ListFinancialEventsByNextTokenRequest listFinancialEventsByNextTokenRequest = new ListFinancialEventsByNextTokenRequest();
        listFinancialEventsByNextTokenRequest.setSellerId(sellerId);
        listFinancialEventsByNextTokenRequest.setMWSAuthToken(mwsAuthToken);
        listFinancialEventsByNextTokenRequest.setNextToken(nextToken);
        listFinancialEventsByNextTokenRequests.add(listFinancialEventsByNextTokenRequest);
        List<Object> listFinancialEventsByNextTokenList = invokeListFinancialEventsByNextToken(client, listFinancialEventsByNextTokenRequests);
        ListFinancialEventsByNextTokenResponse listFinancialEventsByNextTokenResponse = (ListFinancialEventsByNextTokenResponse) (listFinancialEventsByNextTokenList.get(0));
        financialEventsList.add(listFinancialEventsByNextTokenResponse.getListFinancialEventsByNextTokenResult().getFinancialEvents());
        log.info("当前financialEvents size：" + financialEventsList.size());
        String nextToken1 = listFinancialEventsByNextTokenResponse.getListFinancialEventsByNextTokenResult().getNextToken();
        if (nextToken1 != null) {
            getFinancialEventsListByNextToken(financialEventsList, client, sellerId, mwsAuthToken, nextToken1);
        }
        return financialEventsList;
    }


    /**
     * 封装financialEvents数据和financialEventGroups
     * <p>
     * 需要根据具体财务数据中的站点信息才能确定是哪个国家的
     */
    private HashMap<String, List> packageFinancialEventsAndGroup(HashMap<String, List<FinancialEvents>> financialEventsListMap, List<FinancialEventGroup> financialEventGroupList, String sellerId, String brandName) {
        HashMap<String, List> resultMap = new HashMap<>(3);
        List<MwsFinancesFinancialReport> finalMwsFinancesFinancialReportList = new ArrayList<>();
        List<MwsFinancesEventGroup> mwsFinancesEventGroupList = new ArrayList<>();
        List<MwsFinancesInfrequentlyUsed> mwsFinancesInfrequentlyUsedList = new ArrayList<>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Set<Map.Entry<String, List<FinancialEvents>>> entries = financialEventsListMap.entrySet();
        for (Map.Entry<String, List<FinancialEvents>> entry : entries) {
            List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList = new ArrayList<>();
            //这里是一组账期的数据
            String groupId = entry.getKey();
            //初始化countryCode
            String countryCode = null;
            List<FinancialEvents> financialEventsList = entry.getValue();
            for (FinancialEvents financialEvents : financialEventsList) {
                //暂时常用的财务事件是这些，其他的之后再加
                //ServiceFeeEventList serviceFeeEvent
                if (null != financialEvents.getServiceFeeEventList() && financialEvents.getServiceFeeEventList().size() != 0) {
                    List<ServiceFeeEvent> serviceFeeEventList = financialEvents.getServiceFeeEventList();
                    mwsFinancesFinancialReportList.addAll(packageServiceFeeEvents(serviceFeeEventList, sellerId, brandName, groupId));
                }
                //ShipmentEventList shipmentEvent
                if (null != financialEvents.getShipmentEventList() && financialEvents.getShipmentEventList().size() != 0) {
                    List<ShipmentEvent> shipmentEventList = financialEvents.getShipmentEventList();
                    mwsFinancesFinancialReportList.addAll(packageShipmentEvents(shipmentEventList, sellerId, brandName, groupId));
                }
                //RefundEventList ShipmentEvent
                if (null != financialEvents.getRefundEventList() && financialEvents.getRefundEventList().size() != 0) {
                    List<ShipmentEvent> shipmentEventList = financialEvents.getRefundEventList();
                    mwsFinancesFinancialReportList.addAll(packageRefundEvents(shipmentEventList, sellerId, brandName, groupId));

                }
                //AdjustmentEventList adjustmentEvent
                if (null != financialEvents.getAdjustmentEventList() && financialEvents.getAdjustmentEventList().size() != 0) {
                    List<AdjustmentEvent> adjustmentEventList = financialEvents.getAdjustmentEventList();
                    mwsFinancesFinancialReportList.addAll(packageAdjustmentEvents(adjustmentEventList, sellerId, brandName, groupId));
                }
                //ProductAdsPaymentEventList productAdsPaymentEvent
                if (null != financialEvents.getProductAdsPaymentEventList() && financialEvents.getProductAdsPaymentEventList().size() != 0) {
                    List<ProductAdsPaymentEvent> productAdsPaymentEventList = financialEvents.getProductAdsPaymentEventList();
                    mwsFinancesFinancialReportList.addAll(packageProductAdsPaymentEvents(productAdsPaymentEventList, sellerId, brandName, groupId));
                }
                //CouponPaymentEventList CouponPaymentEvent
                if (null != financialEvents.getCouponPaymentEventList() && financialEvents.getCouponPaymentEventList().size() != 0) {
                    List<CouponPaymentEvent> couponPaymentEventList = financialEvents.getCouponPaymentEventList();
                    mwsFinancesFinancialReportList.addAll(packageCouponPaymentEvents(couponPaymentEventList, sellerId, brandName, groupId));
                }
                //SellerDealPaymentEvent
                if (null != financialEvents.getSellerDealPaymentEventList() && financialEvents.getSellerDealPaymentEventList().size() != 0) {
                    List<SellerDealPaymentEvent> sellerDealPaymentEventList = financialEvents.getSellerDealPaymentEventList();
                    mwsFinancesFinancialReportList.addAll(packageSellerDealPaymentEvents(sellerDealPaymentEventList, sellerId, brandName, groupId));
                }
                //SellerReviewEnrollmentPaymentEvent
                if (null != financialEvents.getSellerReviewEnrollmentPaymentEventList() && financialEvents.getSellerReviewEnrollmentPaymentEventList().size() != 0) {
                    List<SellerReviewEnrollmentPaymentEvent> sellerReviewEnrollmentPaymentEventList = financialEvents.getSellerReviewEnrollmentPaymentEventList();
                    mwsFinancesFinancialReportList.addAll(packageSellerReviewEnrollmentPaymentEvents(sellerReviewEnrollmentPaymentEventList, sellerId, brandName, groupId));
                }
                //DebtRecoveryEvent
                if (null != financialEvents.getDebtRecoveryEventList() && financialEvents.getDebtRecoveryEventList().size() != 0) {
                    List<DebtRecoveryEvent> debtRecoveryEventList = financialEvents.getDebtRecoveryEventList();
                    mwsFinancesFinancialReportList.addAll(packageDebtRecoveryEvents(debtRecoveryEventList, sellerId, brandName, groupId));
                }
                //不常用的暂时不录入数据库，只做一个日志记录
                //RentalTransactionEvent
                if (null != financialEvents.getRentalTransactionEventList() && financialEvents.getRentalTransactionEventList().size() != 0) {
                    log.info("可能包含RentalTransactionEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("RentalTransactionEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //ShipmentSettleEvent
                if (null != financialEvents.getShipmentSettleEventList() && financialEvents.getShipmentSettleEventList().size() != 0) {
                    log.info("可能包含ShipmentSettleEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("ShipmentSettleEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //ServiceProviderCreditEvent
                if (null != financialEvents.getServiceProviderCreditEventList() && financialEvents.getServiceProviderCreditEventList().size() != 0) {
                    log.info("可能包含ServiceProviderCreditEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("ServiceProviderCreditEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //ImagingServicesFeeEvent
                if (null != financialEvents.getImagingServicesFeeEventList() && financialEvents.getImagingServicesFeeEventList().size() != 0) {
                    log.info("可能包含ImagingServicesFeeEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("ImagingServicesFeeEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }

                //GuaranteeClaimEvent
                if (null != financialEvents.getGuaranteeClaimEventList() && financialEvents.getGuaranteeClaimEventList().size() != 0) {
                    log.info("可能包含GuaranteeClaimEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("GuaranteeClaimEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //TDSReimbursementEvent
                if (null != financialEvents.getTDSReimbursementEventList() && financialEvents.getTDSReimbursementEventList().size() != 0) {
                    log.info("可能包含TDSReimbursementEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("TDSReimbursementEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //ChargebackEvent
                if (null != financialEvents.getChargebackEventList() && financialEvents.getChargebackEventList().size() != 0) {
                    log.info("可能包含ChargebackEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("ChargebackEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //NetworkComminglingTransactionEvent
                if (null != financialEvents.getNetworkComminglingTransactionEventList() && financialEvents.getNetworkComminglingTransactionEventList().size() != 0) {
                    log.info("可能包含NetworkComminglingTransactionEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("NetworkComminglingTransactionEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //LoanServicingEvent
                if (null != financialEvents.getLoanServicingEventList() && financialEvents.getLoanServicingEventList().size() != 0) {
                    log.info("可能包含LoanServicingEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("LoanServicingEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //RemovalShipmentEvent
                if (null != financialEvents.getRemovalShipmentEventList() && financialEvents.getRemovalShipmentEventList().size() != 0) {
                    log.info("可能包含RemovalShipmentEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("RemovalShipmentEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //PerformanceBondRefundEvent
                if (null != financialEvents.getPerformanceBondRefundEventList() && financialEvents.getPerformanceBondRefundEventList().size() != 0) {
                    log.info("可能包含PerformanceBondRefundEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("PerformanceBondRefundEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //AffordabilityExpenseReversalEvent
                if (null != financialEvents.getAffordabilityExpenseReversalEventList() && financialEvents.getAffordabilityExpenseReversalEventList().size() != 0) {
                    log.info("可能包含AffordabilityExpenseReversalEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("AffordabilityExpenseReversalEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //PayWithAmazonEvent
                if (null != financialEvents.getPayWithAmazonEventList() && financialEvents.getPayWithAmazonEventList().size() != 0) {
                    log.info("可能包含PayWithAmazonEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("PayWithAmazonEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //RetrochargeEvent
                if (null != financialEvents.getRetrochargeEventList() && financialEvents.getRetrochargeEventList().size() != 0) {
                    log.info("可能包含RetrochargeEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("RetrochargeEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //TrialShipmentEvent
                if (null != financialEvents.getTrialShipmentEventList() && financialEvents.getTrialShipmentEventList().size() != 0) {
                    log.info("可能包含TrialShipmentEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("TrialShipmentEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //SAFETReimbursementEvent
                if (null != financialEvents.getSAFETReimbursementEventList() && financialEvents.getSAFETReimbursementEventList().size() != 0) {
                    log.info("可能包含SAFETReimbursementEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("SAFETReimbursementEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //FBALiquidationEvent
                if (null != financialEvents.getFBALiquidationEventList() && financialEvents.getFBALiquidationEventList().size() != 0) {
                    log.info("可能包含FBALiquidationEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("FBALiquidationEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
                //AffordabilityExpenseEvent
                if (null != financialEvents.getAffordabilityExpenseEventList() && financialEvents.getAffordabilityExpenseEventList().size() != 0) {
                    log.info("可能包含AffordabilityExpenseEvent");
                    MwsFinancesInfrequentlyUsed mwsFinancesInfrequentlyUsed = new MwsFinancesInfrequentlyUsed();
                    mwsFinancesInfrequentlyUsed.setFinancialEventGroupId(groupId);
                    mwsFinancesInfrequentlyUsed.setSellerId(sellerId);
                    mwsFinancesInfrequentlyUsed.setContent("AffordabilityExpenseEvent");
                    mwsFinancesInfrequentlyUsedList.add(mwsFinancesInfrequentlyUsed);
                }
            }
            //先从数据库中获取对应这个groupID的countryCode
            countryCode = mwsFinancesFinancialReportMapper.getCountryCodeByGroupId(groupId);
            if (countryCode == null) {
                //遍历以上所有生成的财务数据，有一条数据中有marketplaceId或者marketplaceName，那么其他的所有数据的countryCode都将固定为这个站点对应的国家
                CODE:
                for (MwsFinancesFinancialReport mwsFinancesFinancialReport : mwsFinancesFinancialReportList) {
                    if (null != mwsFinancesFinancialReport.getMarketplaceName()) {
                        String marketplaceName = mwsFinancesFinancialReport.getMarketplaceName();
                        if (marketplaceName.equals("Non-Amazon")) {
                            continue CODE;
                        }
                        countryCode = AreaCastUtil.castToCountryCodeByMarketplaceName(marketplaceName);
                        break CODE;
                    }
                }
            }
            //为每条财务数据加上这个countryCode
            if (countryCode != null) {
                for (MwsFinancesFinancialReport mwsFinancesFinancialReport : mwsFinancesFinancialReportList) {
                    mwsFinancesFinancialReport.setCountryCode(countryCode);
                }
            }
            finalMwsFinancesFinancialReportList.addAll(mwsFinancesFinancialReportList);
            //确定是哪一个financialEventGroups
            for (FinancialEventGroup eventGroup : financialEventGroupList) {
                String financialEventGroupId = eventGroup.getFinancialEventGroupId();
                if (groupId.equals(financialEventGroupId)) {
                    MwsFinancesEventGroup mwsFinancesEventGroup = packageFinancialEventGroup(eventGroup, brandName, sellerId, countryCode);
                    mwsFinancesEventGroupList.add(mwsFinancesEventGroup);
                    break;
                }
            }
        }
        resultMap.put("mwsFinancesFinancialReportList", finalMwsFinancesFinancialReportList);
        resultMap.put("mwsFinancesEventGroupList", mwsFinancesEventGroupList);
        resultMap.put("mwsFinancesInfrequentlyUsedList", mwsFinancesInfrequentlyUsedList);
        return resultMap;
    }


    /**
     * 封装serviceFeeEvent
     */
    private List<MwsFinancesFinancialReport> packageServiceFeeEvents(List<ServiceFeeEvent> serviceFeeEventList, String sellerId, String brandName, String groupId) {
        //获得当前数据获取的时间
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String createTime = LocalDateTime.now().format(df);
        String dataTime = LocalDateTime.now().minusDays(1).format(df);
        List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList = new ArrayList<>();
        for (ServiceFeeEvent serviceFeeEvent : serviceFeeEventList) {
            String transactionType = "other-transaction";
            String amazonOrderId = null;
            if (null != serviceFeeEvent.getAmazonOrderId()) {
                amazonOrderId = serviceFeeEvent.getAmazonOrderId();
            }
            String feeReason = null;
            if (null != serviceFeeEvent.getFeeReason()) {
                feeReason = serviceFeeEvent.getFeeReason();
            }
            String sellerSKU = null;
            if (null != serviceFeeEvent.getSellerSKU()) {
                sellerSKU = serviceFeeEvent.getSellerSKU();
            }
            String asin = null;
            if (null != serviceFeeEvent.getASIN()) {
                asin = serviceFeeEvent.getASIN();
            }
            String feeDescription = null;
            if (null != serviceFeeEvent.getFeeDescription()) {
                feeDescription = serviceFeeEvent.getFeeDescription();
            }
            String fnSKU = null;
            if (null != serviceFeeEvent.getFnSKU()) {
                fnSKU = serviceFeeEvent.getFnSKU();
            }
            if (null != serviceFeeEvent.getFeeList()) {
                List<FeeComponent> feeList = serviceFeeEvent.getFeeList();
                for (FeeComponent feeComponent : feeList) {
                    String feeType = feeComponent.getFeeType();
                    Currency feeAmount = feeComponent.getFeeAmount();
                    String currencyCode = null;
                    if (null != feeAmount.getCurrencyCode())
                        currencyCode = feeAmount.getCurrencyCode();
                    BigDecimal currencyAmount = null;
                    if (null != feeAmount.getCurrencyAmount())
                        currencyAmount = feeAmount.getCurrencyAmount();
                    if (null != currencyAmount && currencyAmount.compareTo(BigDecimal.ZERO) != 0) {
                        MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
                        mwsFinancesFinancialReport.setSellerId(sellerId);
                        mwsFinancesFinancialReport.setBrandName(brandName);
                        mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
                        mwsFinancesFinancialReport.setAmazonOrderId(amazonOrderId);
                        mwsFinancesFinancialReport.setSku(sellerSKU);
                        mwsFinancesFinancialReport.setAsin(asin);
                        mwsFinancesFinancialReport.setFnsku(fnSKU);
                        mwsFinancesFinancialReport.setFeeDescription(feeDescription);
                        mwsFinancesFinancialReport.setTransactionType(transactionType);
                        mwsFinancesFinancialReport.setCurrency(currencyCode);
                        mwsFinancesFinancialReport.setAmount(currencyAmount);
                        mwsFinancesFinancialReport.setPostedDate(dataTime);
                        mwsFinancesFinancialReport.setAmountDescription(feeType);
                        mwsFinancesFinancialReport.setRemark(feeReason);
                        mwsFinancesFinancialReport.setCreateTime(createTime);
                        mwsFinancesFinancialReport.setFinanceStatus(1);
                        mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
                    }

                }
            }
        }
        return mwsFinancesFinancialReportList;
    }

    /**
     * 封装shipmentEvent
     */
    private List<MwsFinancesFinancialReport> packageShipmentEvents(List<ShipmentEvent> shipmentEventList, String sellerId, String brandName, String groupId) {
        List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList = new ArrayList<>();
        String transactionType = "Order";
        mwsFinancesFinancialReportList = handleShipmentEvent(shipmentEventList, sellerId, brandName, groupId, transactionType);
        return mwsFinancesFinancialReportList;
    }


    /**
     * 封装RefundEventList(ShipmentEvent)
     */
    private List<MwsFinancesFinancialReport> packageRefundEvents(List<ShipmentEvent> shipmentEventList, String sellerId, String brandName, String groupId) {
        List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList = new ArrayList<>();
        String transactionType = "Refund";
        mwsFinancesFinancialReportList = handleShipmentEvent(shipmentEventList, sellerId, brandName, groupId, transactionType);
        return mwsFinancesFinancialReportList;
    }

    /**
     * 封装AdjustmentEvents
     */
    private List<MwsFinancesFinancialReport> packageAdjustmentEvents(List<AdjustmentEvent> adjustmentEventList, String sellerId, String brandName, String groupId) {
        List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList = new ArrayList<>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (AdjustmentEvent adjustmentEvent : adjustmentEventList) {
            String transactionType = "Adjustment";
            String adjustmentType = null;
            if (null != adjustmentEvent.getAdjustmentType()) {
                adjustmentType = adjustmentEvent.getAdjustmentType();
            }
            String postedDate = null;
            if (null != adjustmentEvent.getPostedDate()) {
                XMLGregorianCalendar postedDate1 = adjustmentEvent.getPostedDate();
                postedDate = LocalDateTime.of(postedDate1.getYear(), postedDate1.getMonth(), postedDate1.getDay(), postedDate1.getHour(), postedDate1.getMinute(), postedDate1.getSecond()).format(df);
            }
            if (null != adjustmentEvent.getAdjustmentItemList()) {
                List<AdjustmentItem> adjustmentItemList = adjustmentEvent.getAdjustmentItemList();
                for (AdjustmentItem adjustmentItem : adjustmentItemList) {
                    String quantity = null;
                    if (null != adjustmentItem.getQuantity()) {
                        quantity = adjustmentItem.getQuantity();
                    }
                    String currencyCode = null;
                    BigDecimal currencyAmount = null;
                    if (null != adjustmentItem.getTotalAmount()) {
                        Currency totalAmount = adjustmentItem.getTotalAmount();
                        if (null != totalAmount.getCurrencyCode())
                            currencyCode = totalAmount.getCurrencyCode();
                        if (null != totalAmount.getCurrencyAmount())
                            currencyAmount = totalAmount.getCurrencyAmount();
                    }
                    String sellerSKU = null;
                    if (null != adjustmentItem.getSellerSKU()) {
                        sellerSKU = adjustmentItem.getSellerSKU();
                    }
                    String productDescription = null;
                    if (null != adjustmentItem.getProductDescription()) {
                        productDescription = adjustmentItem.getProductDescription();
                    }
                    String fnSKU = null;
                    if (null != adjustmentItem.getFnSKU()) {
                        fnSKU = adjustmentItem.getFnSKU();
                    }
                    String asin = null;
                    if (null != adjustmentItem.getASIN()) {
                        asin = adjustmentItem.getASIN();
                    }
                    if (null != currencyAmount && currencyAmount.compareTo(BigDecimal.ZERO) != 0) {
                        MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
                        mwsFinancesFinancialReport.setSellerId(sellerId);
                        mwsFinancesFinancialReport.setBrandName(brandName);
                        mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
                        mwsFinancesFinancialReport.setSku(sellerSKU);
                        mwsFinancesFinancialReport.setAsin(asin);
                        mwsFinancesFinancialReport.setFnsku(fnSKU);
                        mwsFinancesFinancialReport.setTransactionType(transactionType);
                        mwsFinancesFinancialReport.setQuantityPurchased(Long.parseLong(quantity));
                        mwsFinancesFinancialReport.setCurrency(currencyCode);
                        mwsFinancesFinancialReport.setAmount(currencyAmount);
                        mwsFinancesFinancialReport.setAmountDescription(adjustmentType);
                        mwsFinancesFinancialReport.setPostedDate(postedDate);
                        mwsFinancesFinancialReport.setProductDescription(productDescription);
                        mwsFinancesFinancialReport.setFinanceStatus(1);
                        mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
                    }
                }
            }
        }
        return mwsFinancesFinancialReportList;
    }

    /**
     * 封装ProductAdsPaymentEvent
     */
    private List<MwsFinancesFinancialReport> packageProductAdsPaymentEvents(List<ProductAdsPaymentEvent> productAdsPaymentEventList, String sellerId, String brandName, String groupId) {
        List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList = new ArrayList<>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (ProductAdsPaymentEvent productAdsPaymentEvent : productAdsPaymentEventList) {
            String transactionType = "ServiceFee";
            String amountType = "Cost of Advertising";
            String amountDescription = "Cost of Advertising";
            String postedDate = null;
            if (null != productAdsPaymentEvent.getPostedDate()) {
                XMLGregorianCalendar postedDate1 = productAdsPaymentEvent.getPostedDate();
                postedDate = LocalDateTime.of(postedDate1.getYear(), postedDate1.getMonth(), postedDate1.getDay(), postedDate1.getHour(), postedDate1.getMinute(), postedDate1.getSecond()).format(df);
            }
            String invoiceId = null;
            if (null != productAdsPaymentEvent.getInvoiceId()) {
                invoiceId = productAdsPaymentEvent.getInvoiceId();
            }
            String currencyCode = null;
            BigDecimal currencyAmount = null;
            if (null != productAdsPaymentEvent.getTransactionValue()) {
                Currency transactionValue = productAdsPaymentEvent.getTransactionValue();
                if (null != transactionValue.getCurrencyCode())
                    currencyCode = transactionValue.getCurrencyCode();
                if (null != transactionValue.getCurrencyAmount())
                    currencyAmount = transactionValue.getCurrencyAmount();
            }
            if (null != currencyAmount && currencyAmount.compareTo(BigDecimal.ZERO) != 0) {
                MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
                mwsFinancesFinancialReport.setSellerId(sellerId);
                mwsFinancesFinancialReport.setBrandName(brandName);
                mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
                mwsFinancesFinancialReport.setTransactionType(transactionType);
                mwsFinancesFinancialReport.setCurrency(currencyCode);
                mwsFinancesFinancialReport.setAmount(currencyAmount);
                mwsFinancesFinancialReport.setAmountType(amountType);
                mwsFinancesFinancialReport.setAmountDescription(amountDescription);
                mwsFinancesFinancialReport.setPostedDate(postedDate);
                mwsFinancesFinancialReport.setAssociationId(invoiceId);
                mwsFinancesFinancialReport.setFinanceStatus(1);
                mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
            }
        }
        return mwsFinancesFinancialReportList;
    }

    /**
     * 封装CouponPaymentEvents
     */
    private List<MwsFinancesFinancialReport> packageCouponPaymentEvents(List<CouponPaymentEvent> couponPaymentEventList, String sellerId, String brandName, String groupId) {
        List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList = new ArrayList<>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (CouponPaymentEvent couponPaymentEvent : couponPaymentEventList) {
            String transactionType = "CouponRedemptionFee";
            String amountType = "CouponRedemptionFee";
            String postedDate = null;
            if (null != couponPaymentEvent.getPostedDate()) {
                XMLGregorianCalendar postedDate1 = couponPaymentEvent.getPostedDate();
                postedDate = LocalDateTime.of(postedDate1.getYear(), postedDate1.getMonth(), postedDate1.getDay(), postedDate1.getHour(), postedDate1.getMinute(), postedDate1.getSecond()).format(df);
            }
            String couponId = null;
            if (null != couponPaymentEvent.getCouponId()) {
                couponId = couponPaymentEvent.getCouponId();
            }
            String sellerCouponDescription = null;
            if (null != couponPaymentEvent.getSellerCouponDescription()) {
                sellerCouponDescription = couponPaymentEvent.getSellerCouponDescription();
            }
            Long clipOrRedemptionCount = null;
            if (null != couponPaymentEvent.getClipOrRedemptionCount()) {
                clipOrRedemptionCount = couponPaymentEvent.getClipOrRedemptionCount();
            }
            String paymentEventId = null;
            if (null != couponPaymentEvent.getPaymentEventId()) {
                paymentEventId = couponPaymentEvent.getPaymentEventId();
            }
            String currencyCode = null;
            BigDecimal currencyAmount = null;
            if (null != couponPaymentEvent.getTotalAmount()) {
                Currency totalAmount = couponPaymentEvent.getTotalAmount();
                if (null != totalAmount.getCurrencyCode())
                    currencyCode = totalAmount.getCurrencyCode();
                if (null != totalAmount.getCurrencyAmount())
                    currencyAmount = totalAmount.getCurrencyAmount();
            }
            if (null != currencyAmount && currencyAmount.compareTo(BigDecimal.ZERO) != 0) {
                MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
                mwsFinancesFinancialReport.setSellerId(sellerId);
                mwsFinancesFinancialReport.setBrandName(brandName);
                mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
                mwsFinancesFinancialReport.setAmazonOrderId(paymentEventId);
                mwsFinancesFinancialReport.setTransactionType(transactionType);
                mwsFinancesFinancialReport.setQuantityPurchased(clipOrRedemptionCount);
                mwsFinancesFinancialReport.setCurrency(currencyCode);
                mwsFinancesFinancialReport.setAmount(currencyAmount);
                mwsFinancesFinancialReport.setAmountType(amountType);
                mwsFinancesFinancialReport.setAmountDescription(amountType);
                mwsFinancesFinancialReport.setRemark(sellerCouponDescription);
                mwsFinancesFinancialReport.setPostedDate(postedDate);
                mwsFinancesFinancialReport.setCouponId(couponId);
                mwsFinancesFinancialReport.setFinanceStatus(1);
                mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
            }
        }
        return mwsFinancesFinancialReportList;
    }

    /**
     * 封装SellerDealPaymentEvents
     */
    private List<MwsFinancesFinancialReport> packageSellerDealPaymentEvents(List<SellerDealPaymentEvent> sellerDealPaymentEventList, String sellerId, String brandName, String groupId) {
        List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList = new ArrayList<>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (SellerDealPaymentEvent sellerDealPaymentEvent : sellerDealPaymentEventList) {
            String transactionType = "LightningDealFee";
            String amountType = "LightningDealFee";
            String dealId = null;
            if (null != sellerDealPaymentEvent.getDealId()) {
                dealId = sellerDealPaymentEvent.getDealId();
            }
            String postedDate = null;
            if (null != sellerDealPaymentEvent.getPostedDate()) {
                XMLGregorianCalendar postedDate1 = sellerDealPaymentEvent.getPostedDate();
                postedDate = LocalDateTime.of(postedDate1.getYear(), postedDate1.getMonth(), postedDate1.getDay(), postedDate1.getHour(), postedDate1.getMinute(), postedDate1.getSecond()).format(df);
            }
            String feeType = null;
            if (null != sellerDealPaymentEvent.getFeeType()) {
                feeType = sellerDealPaymentEvent.getFeeType();
            }
            String currencyCode = null;
            BigDecimal currencyAmount = null;
            if (null != sellerDealPaymentEvent.getTotalAmount()) {
                Currency totalAmount = sellerDealPaymentEvent.getTotalAmount();
                if (null != totalAmount.getCurrencyCode())
                    currencyCode = totalAmount.getCurrencyCode();
                if (null != totalAmount.getCurrencyAmount())
                    currencyAmount = totalAmount.getCurrencyAmount();
            }
            if (null != currencyAmount && currencyAmount.compareTo(BigDecimal.ZERO) != 0) {
                MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
                mwsFinancesFinancialReport.setSellerId(sellerId);
                mwsFinancesFinancialReport.setBrandName(brandName);
                mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
                mwsFinancesFinancialReport.setTransactionType(transactionType);
                mwsFinancesFinancialReport.setCurrency(currencyCode);
                mwsFinancesFinancialReport.setAmount(currencyAmount);
                mwsFinancesFinancialReport.setAmountType(amountType);
                mwsFinancesFinancialReport.setAmountDescription(feeType);
                mwsFinancesFinancialReport.setPostedDate(postedDate);
                mwsFinancesFinancialReport.setMerchantOrderId(dealId);
                mwsFinancesFinancialReport.setFinanceStatus(1);
                mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
            }
        }
        return mwsFinancesFinancialReportList;
    }

    /**
     * 封装SellerReviewEnrollmentPaymentEvents
     */
    private List<MwsFinancesFinancialReport> packageSellerReviewEnrollmentPaymentEvents(List<SellerReviewEnrollmentPaymentEvent> sellerReviewEnrollmentPaymentEventList, String sellerId, String brandName, String groupId) {
        List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList = new ArrayList<>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (SellerReviewEnrollmentPaymentEvent sellerReviewEnrollmentPaymentEvent : sellerReviewEnrollmentPaymentEventList) {
            String transactionType = "SellerReviewEnrollmentPayment";
            String amountType = "Review Enrollment Fee";
            String amountDescription = "Early Reviewer Program fee";
            String postedDate = null;
            if (null != sellerReviewEnrollmentPaymentEvent.getPostedDate()) {
                XMLGregorianCalendar postedDate1 = sellerReviewEnrollmentPaymentEvent.getPostedDate();
                postedDate = LocalDateTime.of(postedDate1.getYear(), postedDate1.getMonth(), postedDate1.getDay(), postedDate1.getHour(), postedDate1.getMinute(), postedDate1.getSecond()).format(df);
            }
            String enrollmentId = null;
            if (null != sellerReviewEnrollmentPaymentEvent.getEnrollmentId()) {
                enrollmentId = sellerReviewEnrollmentPaymentEvent.getEnrollmentId();
            }
            String parentASIN = null;
            if (null != sellerReviewEnrollmentPaymentEvent.getParentASIN()) {
                parentASIN = sellerReviewEnrollmentPaymentEvent.getParentASIN();
            }
            String currencyCode = null;
            BigDecimal currencyAmount = null;
            if (null != sellerReviewEnrollmentPaymentEvent.getTotalAmount()) {
                Currency totalAmount = sellerReviewEnrollmentPaymentEvent.getTotalAmount();
                if (null != totalAmount.getCurrencyCode())
                    currencyCode = totalAmount.getCurrencyCode();
                if (null != totalAmount.getCurrencyAmount())
                    currencyAmount = totalAmount.getCurrencyAmount();
            }
            if (null != currencyAmount && currencyAmount.compareTo(BigDecimal.ZERO) != 0) {
                MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
                mwsFinancesFinancialReport.setSellerId(sellerId);
                mwsFinancesFinancialReport.setBrandName(brandName);
                mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
                mwsFinancesFinancialReport.setAsin(parentASIN);
                mwsFinancesFinancialReport.setTransactionType(transactionType);
                mwsFinancesFinancialReport.setCurrency(currencyCode);
                mwsFinancesFinancialReport.setAmount(currencyAmount);
                mwsFinancesFinancialReport.setAmountType(amountType);
                mwsFinancesFinancialReport.setAmountDescription(amountDescription);
                mwsFinancesFinancialReport.setPostedDate(postedDate);
                mwsFinancesFinancialReport.setMerchantOrderId(enrollmentId);
                mwsFinancesFinancialReport.setFinanceStatus(1);
                mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
            }
        }
        return mwsFinancesFinancialReportList;
    }

    /**
     * 封装DebtRecoveryEvents
     */
    private List<MwsFinancesFinancialReport> packageDebtRecoveryEvents(List<DebtRecoveryEvent> debtRecoveryEventList, String sellerId, String brandName, String groupId) {
        List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList = new ArrayList<>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (DebtRecoveryEvent debtRecoveryEvent : debtRecoveryEventList) {
            String transactionType = "other-transaction";
            String amountType = "other-transaction";
            String amountDescription = "Successful charge";
            String postedDate = null;
            String currencyCode = null;
            BigDecimal currencyAmount = null;
            if (null != debtRecoveryEvent.getOverPaymentCredit()) {
                Currency totalAmount = debtRecoveryEvent.getOverPaymentCredit();
                if (null != totalAmount.getCurrencyCode())
                    currencyCode = totalAmount.getCurrencyCode();
                if (null != totalAmount.getCurrencyAmount())
                    currencyAmount = totalAmount.getCurrencyAmount();
            }
            if (null != debtRecoveryEvent.getDebtRecoveryItemList()) {
                List<DebtRecoveryItem> debtRecoveryItemList = debtRecoveryEvent.getDebtRecoveryItemList();
                String amountType1 = "other-transaction";
                String amountDescription1 = "Payable to Amazon";
                for (DebtRecoveryItem debtRecoveryItem:debtRecoveryItemList){
                    if (null != debtRecoveryItem.getGroupEndDate()) {
                        XMLGregorianCalendar postedDate1 = debtRecoveryItem.getGroupEndDate();
                        postedDate = LocalDateTime.of(postedDate1.getYear(), postedDate1.getMonth(), postedDate1.getDay(), postedDate1.getHour(), postedDate1.getMinute(), postedDate1.getSecond()).format(df);
                    }
                    String currencyCode1 = null;
                    BigDecimal currencyAmount1 = null;
                    if (null != debtRecoveryItem.getOriginalAmount()) {
                        Currency totalAmount = debtRecoveryItem.getOriginalAmount();
                        if (null != totalAmount.getCurrencyCode())
                            currencyCode = totalAmount.getCurrencyCode();
                        if (null != totalAmount.getCurrencyAmount())
                            currencyAmount = totalAmount.getCurrencyAmount();
                    }
                    if (null != currencyAmount1 && currencyAmount1.compareTo(BigDecimal.ZERO) != 0) {
                        MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
                        mwsFinancesFinancialReport.setSellerId(sellerId);
                        mwsFinancesFinancialReport.setBrandName(brandName);
                        mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
                        mwsFinancesFinancialReport.setTransactionType(transactionType);
                        mwsFinancesFinancialReport.setCurrency(currencyCode1);
                        mwsFinancesFinancialReport.setAmount(currencyAmount1);
                        mwsFinancesFinancialReport.setAmountType(amountType1);
                        mwsFinancesFinancialReport.setAmountDescription(amountDescription1);
                        mwsFinancesFinancialReport.setPostedDate(postedDate);
                        mwsFinancesFinancialReport.setFinanceStatus(1);
                        mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
                    }
                }
            }
            if (null != currencyAmount && currencyAmount.compareTo(BigDecimal.ZERO) != 0) {
                MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
                mwsFinancesFinancialReport.setSellerId(sellerId);
                mwsFinancesFinancialReport.setBrandName(brandName);
                mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
                mwsFinancesFinancialReport.setTransactionType(transactionType);
                mwsFinancesFinancialReport.setCurrency(currencyCode);
                mwsFinancesFinancialReport.setAmount(currencyAmount);
                mwsFinancesFinancialReport.setAmountType(amountType);
                mwsFinancesFinancialReport.setAmountDescription(amountDescription);
                mwsFinancesFinancialReport.setPostedDate(postedDate);
                mwsFinancesFinancialReport.setFinanceStatus(1);
                mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
            }
        }
        return mwsFinancesFinancialReportList;
    }


//    /**
//     * 封装账期数据
//     */
//    private List<MwsFinancesEventGroup> packageFinancialEventGroups(List<FinancialEventGroup> financialEventGroupList, String brandName, String sellerId, String countryCode) {
//        //获得当前数据获取的时间
//        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String createTime = LocalDateTime.now().format(df);
//        List<MwsFinancesEventGroup> mwsFinancesEventGroupList = new ArrayList<>();
//        for (FinancialEventGroup financialEventGroup : financialEventGroupList) {
//            String financialEventGroupId = null;
//            if (null != financialEventGroup.getFinancialEventGroupId()) {
//                financialEventGroupId = financialEventGroup.getFinancialEventGroupId();
//            }
//            String processingStatus = null;
//            if (null != financialEventGroup.getProcessingStatus()) {
//                processingStatus = financialEventGroup.getProcessingStatus();
//            }
//            String fundTransferStatus = null;
//            if (null != financialEventGroup.getFundTransferStatus()) {
//                fundTransferStatus = financialEventGroup.getFundTransferStatus();
//            }
//            String originalTotalCurrencyCode = null;
//            BigDecimal originalTotalCurrencyAmount = null;
//            if (null != financialEventGroup.getOriginalTotal()) {
//                Currency originalTotal = financialEventGroup.getOriginalTotal();
//                if (null != originalTotal.getCurrencyCode())
//                    originalTotalCurrencyCode = financialEventGroup.getOriginalTotal().getCurrencyCode();
//                if (null != originalTotal.getCurrencyAmount())
//                    originalTotalCurrencyAmount = financialEventGroup.getOriginalTotal().getCurrencyAmount();
//            }
//            String convertedTotalCurrencyCode = null;
//            BigDecimal convertedTotalCurrencyAmount = null;
//            if (null != financialEventGroup.getConvertedTotal()) {
//                Currency convertedTotal = financialEventGroup.getConvertedTotal();
//                if (null != convertedTotal.getCurrencyCode())
//                    convertedTotalCurrencyCode = financialEventGroup.getConvertedTotal().getCurrencyCode();
//                if (null != convertedTotal.getCurrencyAmount())
//                    convertedTotalCurrencyAmount = financialEventGroup.getConvertedTotal().getCurrencyAmount();
//            }
//            String fundTransferDate = null;
//            if (null != financialEventGroup.getFundTransferDate()) {
//                XMLGregorianCalendar fundTransferDate1 = financialEventGroup.getFundTransferDate();
//                fundTransferDate = LocalDateTime.of(fundTransferDate1.getYear(), fundTransferDate1.getMonth(), fundTransferDate1.getDay(), fundTransferDate1.getHour(), fundTransferDate1.getMinute(), fundTransferDate1.getSecond()).format(df);
//            }
//            String traceId = null;
//            if (null != financialEventGroup.getTraceId()) {
//                traceId = financialEventGroup.getTraceId();
//            }
//            String accountTail = null;
//            if (null != financialEventGroup.getAccountTail()) {
//                accountTail = financialEventGroup.getAccountTail();
//            }
//            String beginningBalanceCurrencyCode = null;
//            BigDecimal beginningBalanceCurrencyAmount = null;
//            if (null != financialEventGroup.getBeginningBalance()) {
//                Currency beginningBalance = financialEventGroup.getBeginningBalance();
//                if (null != beginningBalance.getCurrencyCode())
//                    beginningBalanceCurrencyCode = financialEventGroup.getBeginningBalance().getCurrencyCode();
//                if (null != beginningBalance.getCurrencyAmount())
//                    beginningBalanceCurrencyAmount = financialEventGroup.getBeginningBalance().getCurrencyAmount();
//            }
//            String financialEventGroupStart = null;
//            if (null != financialEventGroup.getFinancialEventGroupStart()) {
//                XMLGregorianCalendar financialEventGroupStart1 = financialEventGroup.getFinancialEventGroupStart();
//                financialEventGroupStart = LocalDateTime.of(financialEventGroupStart1.getYear(), financialEventGroupStart1.getMonth(), financialEventGroupStart1.getDay(), financialEventGroupStart1.getHour(), financialEventGroupStart1.getMinute(), financialEventGroupStart1.getSecond()).format(df);
//            }
//            String financialEventGroupEnd = null;
//            if (null != financialEventGroup.getFinancialEventGroupEnd()) {
//                XMLGregorianCalendar financialEventGroupEnd1 = financialEventGroup.getFinancialEventGroupEnd();
//                financialEventGroupEnd = LocalDateTime.of(financialEventGroupEnd1.getYear(), financialEventGroupEnd1.getMonth(), financialEventGroupEnd1.getDay(), financialEventGroupEnd1.getHour(), financialEventGroupEnd1.getMinute(), financialEventGroupEnd1.getSecond()).format(df);
//            }
//            MwsFinancesEventGroup mwsFinancesEventGroup = new MwsFinancesEventGroup();
//            mwsFinancesEventGroup.setBrandName(brandName);
//            mwsFinancesEventGroup.setSellerId(sellerId);
//            mwsFinancesEventGroup.setCountryCode(countryCode);
//            mwsFinancesEventGroup.setFinancialEventGroupId(financialEventGroupId);
//            mwsFinancesEventGroup.setProcessingStatus(processingStatus);
//            mwsFinancesEventGroup.setFundTransferStatus(fundTransferStatus);
//            mwsFinancesEventGroup.setOriginalTotalCurrencyCode(originalTotalCurrencyCode);
//            mwsFinancesEventGroup.setOriginalTotalCurrencyAmount(originalTotalCurrencyAmount);
//            mwsFinancesEventGroup.setConvertedTotalCurrencyCode(convertedTotalCurrencyCode);
//            mwsFinancesEventGroup.setConvertedTotalCurrencyAmount(convertedTotalCurrencyAmount);
//            mwsFinancesEventGroup.setFundTransferDate(fundTransferDate);
//            mwsFinancesEventGroup.setTraceId(traceId);
//            mwsFinancesEventGroup.setAccountTail(accountTail);
//            mwsFinancesEventGroup.setBeginningBalanceCurrencyCode(beginningBalanceCurrencyCode);
//            mwsFinancesEventGroup.setBeginningBalanceCurrencyAmount(beginningBalanceCurrencyAmount);
//            mwsFinancesEventGroup.setFinancialEventGroupStart(financialEventGroupStart);
//            mwsFinancesEventGroup.setFinancialEventGroupEnd(financialEventGroupEnd);
//            mwsFinancesEventGroup.setCreateTime(createTime);
//            mwsFinancesEventGroupList.add(mwsFinancesEventGroup);
//        }
//        return mwsFinancesEventGroupList;
//    }

    /**
     * 封装账期数据
     */
    private MwsFinancesEventGroup packageFinancialEventGroup(FinancialEventGroup financialEventGroup, String brandName, String sellerId, String countryCode) {
        //获得当前数据获取的时间
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String createTime = LocalDateTime.now().format(df);
        String financialEventGroupId = null;
        if (null != financialEventGroup.getFinancialEventGroupId()) {
            financialEventGroupId = financialEventGroup.getFinancialEventGroupId();
        }
        String processingStatus = null;
        if (null != financialEventGroup.getProcessingStatus()) {
            processingStatus = financialEventGroup.getProcessingStatus();
        }
        String fundTransferStatus = null;
        if (null != financialEventGroup.getFundTransferStatus()) {
            fundTransferStatus = financialEventGroup.getFundTransferStatus();
        }
        String originalTotalCurrencyCode = null;
        BigDecimal originalTotalCurrencyAmount = null;
        if (null != financialEventGroup.getOriginalTotal()) {
            Currency originalTotal = financialEventGroup.getOriginalTotal();
            if (null != originalTotal.getCurrencyCode())
                originalTotalCurrencyCode = financialEventGroup.getOriginalTotal().getCurrencyCode();
            if (null != originalTotal.getCurrencyAmount())
                originalTotalCurrencyAmount = financialEventGroup.getOriginalTotal().getCurrencyAmount();
        }
        String convertedTotalCurrencyCode = null;
        BigDecimal convertedTotalCurrencyAmount = null;
        if (null != financialEventGroup.getConvertedTotal()) {
            Currency convertedTotal = financialEventGroup.getConvertedTotal();
            if (null != convertedTotal.getCurrencyCode())
                convertedTotalCurrencyCode = financialEventGroup.getConvertedTotal().getCurrencyCode();
            if (null != convertedTotal.getCurrencyAmount())
                convertedTotalCurrencyAmount = financialEventGroup.getConvertedTotal().getCurrencyAmount();
        }
        String fundTransferDate = null;
        if (null != financialEventGroup.getFundTransferDate()) {
            XMLGregorianCalendar fundTransferDate1 = financialEventGroup.getFundTransferDate();
            fundTransferDate = LocalDateTime.of(fundTransferDate1.getYear(), fundTransferDate1.getMonth(), fundTransferDate1.getDay(), fundTransferDate1.getHour(), fundTransferDate1.getMinute(), fundTransferDate1.getSecond()).format(df);
        }
        String traceId = null;
        if (null != financialEventGroup.getTraceId()) {
            traceId = financialEventGroup.getTraceId();
        }
        String accountTail = null;
        if (null != financialEventGroup.getAccountTail()) {
            accountTail = financialEventGroup.getAccountTail();
        }
        String beginningBalanceCurrencyCode = null;
        BigDecimal beginningBalanceCurrencyAmount = null;
        if (null != financialEventGroup.getBeginningBalance()) {
            Currency beginningBalance = financialEventGroup.getBeginningBalance();
            if (null != beginningBalance.getCurrencyCode())
                beginningBalanceCurrencyCode = financialEventGroup.getBeginningBalance().getCurrencyCode();
            if (null != beginningBalance.getCurrencyAmount())
                beginningBalanceCurrencyAmount = financialEventGroup.getBeginningBalance().getCurrencyAmount();
        }
        String financialEventGroupStart = null;
        if (null != financialEventGroup.getFinancialEventGroupStart()) {
            XMLGregorianCalendar financialEventGroupStart1 = financialEventGroup.getFinancialEventGroupStart();
            financialEventGroupStart = LocalDateTime.of(financialEventGroupStart1.getYear(), financialEventGroupStart1.getMonth(), financialEventGroupStart1.getDay(), financialEventGroupStart1.getHour(), financialEventGroupStart1.getMinute(), financialEventGroupStart1.getSecond()).format(df);
        }
        String financialEventGroupEnd = null;
        if (null != financialEventGroup.getFinancialEventGroupEnd()) {
            XMLGregorianCalendar financialEventGroupEnd1 = financialEventGroup.getFinancialEventGroupEnd();
            financialEventGroupEnd = LocalDateTime.of(financialEventGroupEnd1.getYear(), financialEventGroupEnd1.getMonth(), financialEventGroupEnd1.getDay(), financialEventGroupEnd1.getHour(), financialEventGroupEnd1.getMinute(), financialEventGroupEnd1.getSecond()).format(df);
        }
        MwsFinancesEventGroup mwsFinancesEventGroup = new MwsFinancesEventGroup();
        mwsFinancesEventGroup.setBrandName(brandName);
        mwsFinancesEventGroup.setSellerId(sellerId);
        mwsFinancesEventGroup.setCountryCode(countryCode);
        mwsFinancesEventGroup.setFinancialEventGroupId(financialEventGroupId);
        mwsFinancesEventGroup.setProcessingStatus(processingStatus);
        mwsFinancesEventGroup.setFundTransferStatus(fundTransferStatus);
        mwsFinancesEventGroup.setOriginalTotalCurrencyCode(originalTotalCurrencyCode);
        mwsFinancesEventGroup.setOriginalTotalCurrencyAmount(originalTotalCurrencyAmount);
        mwsFinancesEventGroup.setConvertedTotalCurrencyCode(convertedTotalCurrencyCode);
        mwsFinancesEventGroup.setConvertedTotalCurrencyAmount(convertedTotalCurrencyAmount);
        mwsFinancesEventGroup.setFundTransferDate(fundTransferDate);
        mwsFinancesEventGroup.setTraceId(traceId);
        mwsFinancesEventGroup.setAccountTail(accountTail);
        mwsFinancesEventGroup.setBeginningBalanceCurrencyCode(beginningBalanceCurrencyCode);
        mwsFinancesEventGroup.setBeginningBalanceCurrencyAmount(beginningBalanceCurrencyAmount);
        mwsFinancesEventGroup.setFinancialEventGroupStart(financialEventGroupStart);
        mwsFinancesEventGroup.setFinancialEventGroupEnd(financialEventGroupEnd);
        mwsFinancesEventGroup.setCreateTime(createTime);
        mwsFinancesEventGroup.setFinanceStatus(1);
        return mwsFinancesEventGroup;
    }

    /**
     * shipmentEvent的处理
     */
    private List<MwsFinancesFinancialReport> handleShipmentEvent(List<ShipmentEvent> shipmentEventList, String sellerId, String brandName, String groupId, String transactionType) {
        //获得当前数据获取的时间
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String createTime = LocalDateTime.now().format(df);
        List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList = new ArrayList<>();
        for (ShipmentEvent shipmentEvent : shipmentEventList) {
            String amazonOrderId = null;
            if (null != shipmentEvent.getAmazonOrderId()) {
                amazonOrderId = shipmentEvent.getAmazonOrderId();
            }
            String sellerOrderId = null;
            if (null != shipmentEvent.getSellerOrderId()) {
                sellerOrderId = shipmentEvent.getSellerOrderId();
            }

            String marketplaceName = null;
            if (null != shipmentEvent.getMarketplaceName()) {
                marketplaceName = shipmentEvent.getMarketplaceName();
            }
            String postedDate = null;
            if (null != shipmentEvent.getPostedDate()) {
                XMLGregorianCalendar postedDate1 = shipmentEvent.getPostedDate();
                postedDate = LocalDateTime.of(postedDate1.getYear(), postedDate1.getMonth(), postedDate1.getDay(), postedDate1.getHour(), postedDate1.getMinute(), postedDate1.getSecond()).format(df);
            }
            //具体的OrderChargeList数据
            if (null != shipmentEvent.getOrderChargeList()) {
                List<ChargeComponent> orderChargeList = shipmentEvent.getOrderChargeList();
                handleShipmentEventChargeComponent(sellerId, brandName, groupId, mwsFinancesFinancialReportList, transactionType, amazonOrderId, sellerOrderId, marketplaceName, postedDate, orderChargeList);
            }
            //具体的OrderChargeAdjustmentList
            if (null != shipmentEvent.getOrderChargeAdjustmentList()) {
                List<ChargeComponent> orderChargeAdjustmentList = shipmentEvent.getOrderChargeAdjustmentList();
                handleShipmentEventChargeComponent(sellerId, brandName, groupId, mwsFinancesFinancialReportList, transactionType, amazonOrderId, sellerOrderId, marketplaceName, postedDate, orderChargeAdjustmentList);
            }
            //具体的ShipmentFeeList
            if (null != shipmentEvent.getShipmentFeeList()) {
                List<FeeComponent> shipmentFeeList = shipmentEvent.getShipmentFeeList();
                handleShipmentEventFeeComponent(sellerId, brandName, groupId, mwsFinancesFinancialReportList, transactionType, amazonOrderId, sellerOrderId, marketplaceName, postedDate, shipmentFeeList);
            }
            //ShipmentFeeAdjustmentList
            if (null != shipmentEvent.getShipmentFeeAdjustmentList()) {
                List<FeeComponent> shipmentFeeAdjustmentList = shipmentEvent.getShipmentFeeAdjustmentList();
                handleShipmentEventFeeComponent(sellerId, brandName, groupId, mwsFinancesFinancialReportList, transactionType, amazonOrderId, sellerOrderId, marketplaceName, postedDate, shipmentFeeAdjustmentList);
            }
            //OrderFeeList
            if (null != shipmentEvent.getOrderFeeList()) {
                List<FeeComponent> orderFeeList = shipmentEvent.getOrderFeeList();
                handleShipmentEventFeeComponent(sellerId, brandName, groupId, mwsFinancesFinancialReportList, transactionType, amazonOrderId, sellerOrderId, marketplaceName, postedDate, orderFeeList);
            }
            //OrderFeeAdjustmentList
            if (null != shipmentEvent.getOrderFeeAdjustmentList()) {
                List<FeeComponent> orderFeeAdjustmentList = shipmentEvent.getOrderFeeAdjustmentList();
                handleShipmentEventFeeComponent(sellerId, brandName, groupId, mwsFinancesFinancialReportList, transactionType, amazonOrderId, sellerOrderId, marketplaceName, postedDate, orderFeeAdjustmentList);
            }
            //DirectPaymentList
            if (null != shipmentEvent.getDirectPaymentList()) {
                List<DirectPayment> directPaymentList = shipmentEvent.getDirectPaymentList();
                for (DirectPayment directPayment : directPaymentList) {
                    String directPaymentType = null;
                    if (null != directPayment.getDirectPaymentType()) {
                        directPaymentType = directPayment.getDirectPaymentType();
                    }
                    String currencyCode = null;
                    BigDecimal currencyAmount = null;
                    if (null != directPayment.getDirectPaymentAmount()) {
                        currencyCode = directPayment.getDirectPaymentAmount().getCurrencyCode();
                        currencyAmount = directPayment.getDirectPaymentAmount().getCurrencyAmount();
                    }
                    MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
                    mwsFinancesFinancialReport.setSellerId(sellerId);
                    mwsFinancesFinancialReport.setBrandName(brandName);
                    mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
                    mwsFinancesFinancialReport.setAmazonOrderId(amazonOrderId);
                    mwsFinancesFinancialReport.setMarketplaceName(marketplaceName);
                    mwsFinancesFinancialReport.setTransactionType(transactionType);
                    mwsFinancesFinancialReport.setCurrency(currencyCode);
                    mwsFinancesFinancialReport.setAmount(currencyAmount);
                    mwsFinancesFinancialReport.setAmountDescription(directPaymentType);
                    mwsFinancesFinancialReport.setPostedDate(postedDate);
                    mwsFinancesFinancialReport.setMerchantOrderId(sellerOrderId);
                    mwsFinancesFinancialReport.setCreateTime(createTime);
                    mwsFinancesFinancialReport.setFinanceStatus(1);
                    mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
                }
            }
            //ShipmentItemList
            if (null != shipmentEvent.getShipmentItemList()) {
                List<ShipmentItem> shipmentItemList = shipmentEvent.getShipmentItemList();
                mwsFinancesFinancialReportList.addAll(handleShipmentItems(shipmentItemList, sellerId, brandName, groupId, amazonOrderId, marketplaceName, transactionType, postedDate, sellerOrderId));
            }
            //ShipmentItemAdjustmentList
            if (null != shipmentEvent.getShipmentItemAdjustmentList()) {
                List<ShipmentItem> shipmentItemAdjustmentList = shipmentEvent.getShipmentItemAdjustmentList();
                mwsFinancesFinancialReportList.addAll(handleShipmentItems(shipmentItemAdjustmentList, sellerId, brandName, groupId, amazonOrderId, marketplaceName, transactionType, postedDate, sellerOrderId));
            }
        }
        return mwsFinancesFinancialReportList;
    }

    private void handleShipmentEventFeeComponent(String sellerId, String brandName, String groupId, List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList, String transactionType, String amazonOrderId, String sellerOrderId, String marketplaceName, String postedDate, List<FeeComponent> shipmentFeeList) {
        //获得当前数据获取的时间
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String createTime = LocalDateTime.now().format(df);
        for (FeeComponent feeComponent : shipmentFeeList) {
            String feeType = null;
            if (null != feeComponent.getFeeType()) {
                feeType = feeComponent.getFeeType();
            }
            String currencyCode = null;
            BigDecimal currencyAmount = null;
            if (null != feeComponent.getFeeAmount()) {
                Currency feeAmount = feeComponent.getFeeAmount();
                if (null != feeAmount.getCurrencyCode())
                    currencyCode = feeAmount.getCurrencyCode();
                if (null != feeAmount.getCurrencyAmount())
                    currencyAmount = feeAmount.getCurrencyAmount();
            }
            if (null != currencyAmount && currencyAmount.compareTo(BigDecimal.ZERO) != 0) {
                MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
                mwsFinancesFinancialReport.setSellerId(sellerId);
                mwsFinancesFinancialReport.setBrandName(brandName);
                mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
                mwsFinancesFinancialReport.setAmazonOrderId(amazonOrderId);
                mwsFinancesFinancialReport.setMarketplaceName(marketplaceName);
                mwsFinancesFinancialReport.setTransactionType(transactionType);
                mwsFinancesFinancialReport.setCurrency(currencyCode);
                mwsFinancesFinancialReport.setAmount(currencyAmount);
                mwsFinancesFinancialReport.setAmountDescription(feeType);
                mwsFinancesFinancialReport.setPostedDate(postedDate);
                mwsFinancesFinancialReport.setMerchantOrderId(sellerOrderId);
                mwsFinancesFinancialReport.setCreateTime(createTime);
                mwsFinancesFinancialReport.setFinanceStatus(1);
                mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
            }
        }
    }

    private void handleShipmentEventChargeComponent(String sellerId, String brandName, String groupId, List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList, String transactionType, String amazonOrderId, String sellerOrderId, String marketplaceName, String postedDate, List<ChargeComponent> orderChargeList) {
        //获得当前数据获取的时间
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String createTime = LocalDateTime.now().format(df);
        for (ChargeComponent chargeComponent : orderChargeList) {
            String chargeType = null;
            if (null != chargeComponent.getChargeType()) {
                chargeType = chargeComponent.getChargeType();
            }
            String currencyCode = null;
            BigDecimal currencyAmount = null;
            if (null != chargeComponent.getChargeAmount()) {
                Currency chargeAmount = chargeComponent.getChargeAmount();
                if (null != chargeAmount.getCurrencyCode())
                    currencyCode = chargeAmount.getCurrencyCode();
                if (null != chargeAmount.getCurrencyAmount())
                    currencyAmount = chargeAmount.getCurrencyAmount();
            }
            if (null != currencyAmount && currencyAmount.compareTo(BigDecimal.ZERO) != 0) {
                MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
                mwsFinancesFinancialReport.setSellerId(sellerId);
                mwsFinancesFinancialReport.setBrandName(brandName);
                mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
                mwsFinancesFinancialReport.setAmazonOrderId(amazonOrderId);
                mwsFinancesFinancialReport.setMarketplaceName(marketplaceName);
                mwsFinancesFinancialReport.setTransactionType(transactionType);
                mwsFinancesFinancialReport.setCurrency(currencyCode);
                mwsFinancesFinancialReport.setAmount(currencyAmount);
                mwsFinancesFinancialReport.setAmountDescription(chargeType);
                mwsFinancesFinancialReport.setPostedDate(postedDate);
                mwsFinancesFinancialReport.setMerchantOrderId(sellerOrderId);
                mwsFinancesFinancialReport.setCreateTime(createTime);
                mwsFinancesFinancialReport.setFinanceStatus(1);
                mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
            }
        }
    }

    private List<MwsFinancesFinancialReport> handleShipmentItems(
            List<ShipmentItem> shipmentItemList,
            String sellerId,
            String brandName,
            String groupId,
            String amazonOrderId,
            String marketplaceName,
            String transactionType,
            String postedDate,
            String sellerOrderId) {
        //获得当前数据获取的时间
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String createTime = LocalDateTime.now().format(df);
        List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList = new ArrayList<>();
        for (ShipmentItem shipmentItem : shipmentItemList) {
            String sellerSKU = null;
            if (null != shipmentItem.getSellerSKU()) {
                sellerSKU = shipmentItem.getSellerSKU();
            }
            String orderItemId = null;
            if (null != shipmentItem.getOrderItemId()) {
                orderItemId = shipmentItem.getOrderItemId();
            }
            String orderAdjustmentItemId = null;
            if (null != shipmentItem.getOrderAdjustmentItemId()) {
                orderAdjustmentItemId = shipmentItem.getOrderAdjustmentItemId();
            }
            Integer quantityShipped = null;
            if (null != shipmentItem.getQuantityShipped()) {
                quantityShipped = shipmentItem.getQuantityShipped();
            }
            //ItemChargeList
            if (null != shipmentItem.getItemChargeList()) {
                List<ChargeComponent> itemChargeList = shipmentItem.getItemChargeList();
                String amountType = "ItemCharge";
                for (ChargeComponent chargeComponent : itemChargeList) {
                    String chargeType = null;
                    if (null != chargeComponent.getChargeType()) {
                        chargeType = chargeComponent.getChargeType();
                    }
                    String currencyCode = null;
                    BigDecimal currencyAmount = null;
                    if (null != chargeComponent.getChargeAmount()) {
                        Currency chargeAmount = chargeComponent.getChargeAmount();
                        if (null != chargeAmount.getCurrencyCode())
                            currencyCode = chargeComponent.getChargeAmount().getCurrencyCode();
                        if (null != chargeAmount.getCurrencyAmount())
                            currencyAmount = chargeComponent.getChargeAmount().getCurrencyAmount();
                    }
                    packageShipmentItemsItemChargeReport(sellerId, brandName, groupId, amazonOrderId, marketplaceName, transactionType, postedDate, sellerOrderId, mwsFinancesFinancialReportList, sellerSKU, orderItemId, orderAdjustmentItemId, quantityShipped, amountType, chargeType, currencyCode, currencyAmount, createTime);
                }
            }
            //ItemTaxWithheldList
            if (null != shipmentItem.getItemTaxWithheldList()) {
                List<TaxWithheldComponent> itemTaxWithheldList = shipmentItem.getItemTaxWithheldList();
                String amountType = "ItemTaxWithheld";
                for (TaxWithheldComponent taxWithheldComponent : itemTaxWithheldList) {
                    String taxCollectionModel = null;
                    if (null != taxWithheldComponent.getTaxCollectionModel()) {
                        taxCollectionModel = taxWithheldComponent.getTaxCollectionModel();
                    }
                    if (null != taxWithheldComponent.getTaxesWithheld()) {
                        List<ChargeComponent> taxesWithheld = taxWithheldComponent.getTaxesWithheld();
                        for (ChargeComponent chargeComponent : taxesWithheld) {
                            String chargeType = null;
                            if (null != chargeComponent.getChargeType()) {
                                chargeType = chargeComponent.getChargeType();
                            }
                            String currencyCode = null;
                            BigDecimal currencyAmount = null;
                            if (null != chargeComponent.getChargeAmount()) {
                                Currency chargeAmount = chargeComponent.getChargeAmount();
                                if (null != chargeAmount.getCurrencyCode())
                                    currencyCode = chargeAmount.getCurrencyCode();
                                if (null != chargeAmount.getCurrencyAmount())
                                    currencyAmount = chargeAmount.getCurrencyAmount();
                            }
                            if (currencyAmount != null && currencyAmount.compareTo(BigDecimal.ZERO) != 0) {
                                MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
                                mwsFinancesFinancialReport.setSellerId(sellerId);
                                mwsFinancesFinancialReport.setBrandName(brandName);
                                mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
                                mwsFinancesFinancialReport.setAmazonOrderId(amazonOrderId);
                                mwsFinancesFinancialReport.setMarketplaceName(marketplaceName);
                                mwsFinancesFinancialReport.setSku(sellerSKU);
                                mwsFinancesFinancialReport.setTransactionType(transactionType);
                                mwsFinancesFinancialReport.setQuantityPurchased(Long.valueOf(quantityShipped));
                                mwsFinancesFinancialReport.setCurrency(currencyCode);
                                mwsFinancesFinancialReport.setAmount(currencyAmount);
                                mwsFinancesFinancialReport.setAmountType(amountType);
                                mwsFinancesFinancialReport.setAmountDescription(chargeType);
                                mwsFinancesFinancialReport.setPostedDate(postedDate);
                                mwsFinancesFinancialReport.setMerchantOrderId(sellerOrderId);
                                mwsFinancesFinancialReport.setOrderItemCode(orderItemId);
                                mwsFinancesFinancialReport.setTaxCollectionModel(taxCollectionModel);
                                mwsFinancesFinancialReport.setMerchantAdjustmentItemId(orderAdjustmentItemId);
                                mwsFinancesFinancialReport.setCreateTime(createTime);
                                mwsFinancesFinancialReport.setFinanceStatus(1);
                                mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
                            }
                        }
                    }
                }
            }
            //ItemChargeAdjustmentList
            if (null != shipmentItem.getItemChargeAdjustmentList()) {
                List<ChargeComponent> itemChargeAdjustmentList = shipmentItem.getItemChargeAdjustmentList();
                String amountType = "ItemChargeAdjustment";
                for (ChargeComponent chargeComponent : itemChargeAdjustmentList) {
                    String chargeType = null;
                    if (null != chargeComponent.getChargeType()) {
                        chargeType = chargeComponent.getChargeType();
                    }
                    String currencyCode = null;
                    BigDecimal currencyAmount = null;
                    if (null != chargeComponent.getChargeAmount()) {
                        Currency chargeAmount = chargeComponent.getChargeAmount();
                        if (null != chargeAmount.getCurrencyCode())
                            currencyCode = chargeAmount.getCurrencyCode();
                        if (null != chargeAmount.getCurrencyAmount())
                            currencyAmount = chargeAmount.getCurrencyAmount();
                    }
                    packageShipmentItemsItemChargeReport(sellerId, brandName, groupId, amazonOrderId, marketplaceName, transactionType, postedDate, sellerOrderId, mwsFinancesFinancialReportList, sellerSKU, orderItemId, orderAdjustmentItemId, quantityShipped, amountType, chargeType, currencyCode, currencyAmount, createTime);
                }
            }
            //ItemFeeList
            if (null != shipmentItem.getItemFeeList()) {
                List<FeeComponent> itemFeeList = shipmentItem.getItemFeeList();
                String amountType = "ItemFee";
                handleShipmentItemsFeeComponent(sellerId, brandName, groupId, amazonOrderId, marketplaceName, transactionType, postedDate, sellerOrderId, mwsFinancesFinancialReportList, sellerSKU, orderItemId, orderAdjustmentItemId, quantityShipped, itemFeeList, amountType, createTime);
            }
            //ItemFeeAdjustmentList
            if (null != shipmentItem.getItemFeeAdjustmentList()) {
                List<FeeComponent> itemFeeAdjustmentList = shipmentItem.getItemFeeAdjustmentList();
                String amountType = "ItemFeeAdjustment";
                handleShipmentItemsFeeComponent(sellerId, brandName, groupId, amazonOrderId, marketplaceName, transactionType, postedDate, sellerOrderId, mwsFinancesFinancialReportList, sellerSKU, orderItemId, orderAdjustmentItemId, quantityShipped, itemFeeAdjustmentList, amountType, createTime);
            }
            //PromotionList
            if (null != shipmentItem.getPromotionList()) {
                List<Promotion> promotionList = shipmentItem.getPromotionList();
                String amountType = "Promotion";
                handleShipmentItemsPromotion(sellerId, brandName, groupId, amazonOrderId, marketplaceName, transactionType, postedDate, sellerOrderId, mwsFinancesFinancialReportList, sellerSKU, orderItemId, orderAdjustmentItemId, quantityShipped, promotionList, amountType, createTime);
            }
            //PromotionAdjustmentList
            if (null != shipmentItem.getPromotionAdjustmentList()) {
                List<Promotion> promotionAdjustmentList = shipmentItem.getPromotionAdjustmentList();
                String amountType = "PromotionAdjustment";
                handleShipmentItemsPromotion(sellerId, brandName, groupId, amazonOrderId, marketplaceName, transactionType, postedDate, sellerOrderId, mwsFinancesFinancialReportList, sellerSKU, orderItemId, orderAdjustmentItemId, quantityShipped, promotionAdjustmentList, amountType, createTime);
            }
            //CostOfPointsGranted
            if (null != shipmentItem.getCostOfPointsGranted()) {
                Currency costOfPointsGranted = shipmentItem.getCostOfPointsGranted();
                String currencyCode = costOfPointsGranted.getCurrencyCode();
                BigDecimal currencyAmount = costOfPointsGranted.getCurrencyAmount();
                String amountType = "CostOfPointsGranted";
                if (currencyAmount != null && currencyAmount.compareTo(BigDecimal.ZERO) != 0) {
                    MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
                    mwsFinancesFinancialReport.setSellerId(sellerId);
                    mwsFinancesFinancialReport.setBrandName(brandName);
                    mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
                    mwsFinancesFinancialReport.setAmazonOrderId(amazonOrderId);
                    mwsFinancesFinancialReport.setMarketplaceName(marketplaceName);
                    mwsFinancesFinancialReport.setSku(sellerSKU);
                    mwsFinancesFinancialReport.setTransactionType(transactionType);
                    mwsFinancesFinancialReport.setQuantityPurchased(Long.valueOf(quantityShipped));
                    mwsFinancesFinancialReport.setCurrency(currencyCode);
                    mwsFinancesFinancialReport.setAmount(currencyAmount);
                    mwsFinancesFinancialReport.setAmountType(amountType);
                    mwsFinancesFinancialReport.setPostedDate(postedDate);
                    mwsFinancesFinancialReport.setMerchantOrderId(sellerOrderId);
                    mwsFinancesFinancialReport.setOrderItemCode(orderItemId);
                    mwsFinancesFinancialReport.setMerchantAdjustmentItemId(orderAdjustmentItemId);
                    mwsFinancesFinancialReport.setCreateTime(createTime);
                    mwsFinancesFinancialReport.setFinanceStatus(1);
                    mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
                }
            }
            //CostOfPointsReturned
            if (null != shipmentItem.getCostOfPointsReturned()) {
                Currency costOfPointsReturned = shipmentItem.getCostOfPointsReturned();
                String currencyCode = costOfPointsReturned.getCurrencyCode();
                BigDecimal currencyAmount = costOfPointsReturned.getCurrencyAmount();
                String amountType = "CostOfPointsReturned";
                if (currencyAmount != null && currencyAmount.compareTo(BigDecimal.ZERO) != 0) {
                    MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
                    mwsFinancesFinancialReport.setSellerId(sellerId);
                    mwsFinancesFinancialReport.setBrandName(brandName);
                    mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
                    mwsFinancesFinancialReport.setAmazonOrderId(amazonOrderId);
                    mwsFinancesFinancialReport.setMarketplaceName(marketplaceName);
                    mwsFinancesFinancialReport.setSku(sellerSKU);
                    mwsFinancesFinancialReport.setTransactionType(transactionType);
                    mwsFinancesFinancialReport.setQuantityPurchased(Long.valueOf(quantityShipped));
                    mwsFinancesFinancialReport.setCurrency(currencyCode);
                    mwsFinancesFinancialReport.setAmount(currencyAmount);
                    mwsFinancesFinancialReport.setAmountType(amountType);
                    mwsFinancesFinancialReport.setPostedDate(postedDate);
                    mwsFinancesFinancialReport.setMerchantOrderId(sellerOrderId);
                    mwsFinancesFinancialReport.setOrderItemCode(orderItemId);
                    mwsFinancesFinancialReport.setMerchantAdjustmentItemId(orderAdjustmentItemId);
                    mwsFinancesFinancialReport.setCreateTime(createTime);
                    mwsFinancesFinancialReport.setFinanceStatus(1);
                    mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
                }
            }
        }
        return mwsFinancesFinancialReportList;
    }

    private void handleShipmentItemsPromotion(String sellerId, String brandName, String groupId, String amazonOrderId, String marketplaceName, String transactionType, String postedDate, String sellerOrderId, List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList, String sellerSKU, String orderItemId, String orderAdjustmentItemId, Integer quantityShipped, List<Promotion> promotionList, String amountType, String createTime) {
        for (Promotion promotion : promotionList) {
            String promotionType = null;
            if (null != promotion.getPromotionType()) {
                promotionType = promotion.getPromotionType();
            }
            String promotionId = null;
            if (null != promotion.getPromotionId()) {
                promotionId = promotion.getPromotionId();
            }
            String currencyCode = null;
            BigDecimal currencyAmount = null;
            if (null != promotion.getPromotionAmount()) {
                Currency promotionAmount = promotion.getPromotionAmount();
                if (null != promotionAmount.getCurrencyCode())
                    currencyCode = promotion.getPromotionAmount().getCurrencyCode();
                if (null != promotionAmount.getCurrencyAmount())
                    currencyAmount = promotion.getPromotionAmount().getCurrencyAmount();
            }
            if (currencyAmount != null && currencyAmount.compareTo(BigDecimal.ZERO) != 0) {
                MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
                mwsFinancesFinancialReport.setSellerId(sellerId);
                mwsFinancesFinancialReport.setBrandName(brandName);
                mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
                mwsFinancesFinancialReport.setAmazonOrderId(amazonOrderId);
                mwsFinancesFinancialReport.setMarketplaceName(marketplaceName);
                mwsFinancesFinancialReport.setSku(sellerSKU);
                mwsFinancesFinancialReport.setTransactionType(transactionType);
                mwsFinancesFinancialReport.setQuantityPurchased(Long.valueOf(quantityShipped));
                mwsFinancesFinancialReport.setCurrency(currencyCode);
                mwsFinancesFinancialReport.setAmount(currencyAmount);
                mwsFinancesFinancialReport.setAmountType(amountType);
                mwsFinancesFinancialReport.setAmountDescription(promotionType);
                mwsFinancesFinancialReport.setPostedDate(postedDate);
                mwsFinancesFinancialReport.setAssociationId(promotionId);
                mwsFinancesFinancialReport.setMerchantOrderId(sellerOrderId);
                mwsFinancesFinancialReport.setOrderItemCode(orderItemId);
                mwsFinancesFinancialReport.setMerchantAdjustmentItemId(orderAdjustmentItemId);
                mwsFinancesFinancialReport.setCreateTime(createTime);
                mwsFinancesFinancialReport.setFinanceStatus(1);
                mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
            }
        }
    }

    private void handleShipmentItemsFeeComponent(String sellerId, String brandName, String groupId, String amazonOrderId, String marketplaceName, String transactionType, String postedDate, String sellerOrderId, List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList, String sellerSKU, String orderItemId, String orderAdjustmentItemId, Integer quantityShipped, List<FeeComponent> itemFeeList, String amountType, String createTime) {
        for (FeeComponent feeComponent : itemFeeList) {
            String feeType = null;
            if (null != feeComponent.getFeeType()) {
                feeType = feeComponent.getFeeType();
            }
            String currencyCode = null;
            BigDecimal currencyAmount = null;
            if (null != feeComponent.getFeeAmount()) {
                Currency feeAmount = feeComponent.getFeeAmount();
                if (null != feeAmount.getCurrencyCode())
                    currencyCode = feeComponent.getFeeAmount().getCurrencyCode();
                if (null != feeAmount.getCurrencyAmount())
                    currencyAmount = feeComponent.getFeeAmount().getCurrencyAmount();
            }
            packageShipmentItemsItemChargeReport(sellerId, brandName, groupId, amazonOrderId, marketplaceName, transactionType, postedDate, sellerOrderId, mwsFinancesFinancialReportList, sellerSKU, orderItemId, orderAdjustmentItemId, quantityShipped, amountType, feeType, currencyCode, currencyAmount, createTime);
        }
    }

    private void packageShipmentItemsItemChargeReport(String sellerId, String brandName, String groupId, String amazonOrderId, String marketplaceName, String transactionType, String postedDate, String sellerOrderId, List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList, String sellerSKU, String orderItemId, String orderAdjustmentItemId, Integer quantityShipped, String amountType, String chargeType, String currencyCode, BigDecimal currencyAmount, String createTime) {
        if (currencyAmount != null && currencyAmount.compareTo(BigDecimal.ZERO) != 0) {
            MwsFinancesFinancialReport mwsFinancesFinancialReport = new MwsFinancesFinancialReport();
            mwsFinancesFinancialReport.setSellerId(sellerId);
            mwsFinancesFinancialReport.setBrandName(brandName);
            mwsFinancesFinancialReport.setFinancialEventGroupId(groupId);
            mwsFinancesFinancialReport.setAmazonOrderId(amazonOrderId);
            mwsFinancesFinancialReport.setMarketplaceName(marketplaceName);
            mwsFinancesFinancialReport.setSku(sellerSKU);
            mwsFinancesFinancialReport.setTransactionType(transactionType);
            mwsFinancesFinancialReport.setQuantityPurchased(Long.valueOf(quantityShipped));
            mwsFinancesFinancialReport.setCurrency(currencyCode);
            mwsFinancesFinancialReport.setAmount(currencyAmount);
            mwsFinancesFinancialReport.setAmountType(amountType);
            mwsFinancesFinancialReport.setAmountDescription(chargeType);
            mwsFinancesFinancialReport.setPostedDate(postedDate);
            mwsFinancesFinancialReport.setMerchantOrderId(sellerOrderId);
            mwsFinancesFinancialReport.setOrderItemCode(orderItemId);
            mwsFinancesFinancialReport.setMerchantAdjustmentItemId(orderAdjustmentItemId);
            mwsFinancesFinancialReport.setCreateTime(createTime);
            mwsFinancesFinancialReport.setFinanceStatus(1);
            mwsFinancesFinancialReportList.add(mwsFinancesFinancialReport);
        }
    }
}
